package com.jumi.microservice.controller;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jm.member.common.core.utils.ServletUtils;
import com.jm.member.common.core.web.page.TableDataInfo;
import com.jumi.microservice.common.base.dto.ResponseResult;
import com.jumi.microservice.controller.api.JmLevelUpController;
import com.jumi.microservice.dto.reponse.GoldPromoterReviewPageReponse;
import com.jumi.microservice.dto.reponse.GoldPromoterReviewReponse;
import com.jumi.microservice.dto.reponse.ListLevelDataReponse;
import com.jumi.microservice.dto.request.GoldPromoterReviewQueryRequest;
import com.jumi.microservice.entity.JmGoldPromoterReview;
import com.jumi.microservice.entity.JmPromoterCheckLog;
import com.jumi.microservice.entity.JmUser;
import com.jumi.microservice.entity.JmUserLevelConfig;
import com.jumi.microservice.enums.CheckStatus;
import com.jumi.microservice.enums.LevelCondition;
import com.jumi.microservice.service.IJmGoldPromoterReviewService;
import com.jumi.microservice.service.IJmPromoterCheckLogService;
import com.jumi.microservice.service.IJmUserService;
import com.jumi.microservice.service.PageService;
import com.jumi.microservice.util.WrapperUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 金牌推广商表 前端控制器
 * </p>
 *
 * @author 要挑客户管理团队
 * @since 2020-08-11
 */
@RestController
@RequestMapping("/jm-gold-promoter")
@Transactional
@Api(value = "金牌推广商", tags = {"金牌推广商"})
public class JmGoldPromoterReviewController extends JmLevelUpController{

    @Autowired
    IJmGoldPromoterReviewService service;

    @Autowired
    IJmPromoterCheckLogService logService;

    @Autowired
    IJmUserService userService;

    //    @Autowired
//    IJmIdentityAuthenticationLogService logService;
    @PostMapping("/getInfo")
    @ApiOperation("金牌推广商分页")
    public TableDataInfo<JmGoldPromoterReview> getInfo(GoldPromoterReviewQueryRequest request,
                                                       Integer size, Integer current) throws IllegalAccessException {

        Page page = new Page(current, size);
        QueryWrapper wrapper = WrapperUtil.getWrapper(null, request);
        PageService pageService = (PageService) service;
        page = pageService.getPage(page, wrapper);

        List<GoldPromoterReviewPageReponse> goldRecords = (List<GoldPromoterReviewPageReponse>) page.getRecords();

        for (int i = 0; i < goldRecords.size(); i++) {

            GoldPromoterReviewPageReponse goldFor = goldRecords.get(i);

            if (goldFor.getStatus() == CheckStatus.待审核) {
                goldFor.setShenheTime(null);
            }

            QueryWrapper logWrapper = new QueryWrapper();

            logWrapper.eq("admin_id", goldFor.getAdminId());

            logWrapper.last("limit 0,1");

            List<JmPromoterCheckLog> logOne = (List<JmPromoterCheckLog>) logService.list(logWrapper);

//            JmPromoterCheckLog one = (JmPromoterCheckLog) logOne.getRecords();

            if (ObjectUtil.isNotEmpty(logOne))goldFor.setAdminName(logOne.get(0).getAdminName());

        }

        page.setRecords(goldRecords);

        return PageService.getDataTableInfo(page);
    }

    @PostMapping("/update")
    @ApiOperation("金牌推广商/审核")
    @Transactional
    public ResponseResult update(Integer uid, String message, CheckStatus status) {

        Long adminId = ServletUtils.getLoginId();
        String adminName = ServletUtils.getLoginName();

        JmGoldPromoterReview byId = service.getById(uid);

        JmUser users = userService.getById(uid);

        if (ObjectUtil.isNull(byId)) return ResponseResult.error("未查询到相关记录!");

        byId.setShenheTime(LocalDateTime.now());
        byId.setStatus(status);
        byId.setMessage(message);


        JmPromoterCheckLog log = new JmPromoterCheckLog();
        BeanUtils.copyProperties(byId, log);
        log.setAddTime(LocalDateTime.now());

        if (message.equals("售后行为导致不符合升级条件,系统审核不通过!")) {
            byId.setAdminId(0L);
            log.setAdminName("系统审核");
            log.setAdminId(0L);
        } else {
            byId.setAdminId(adminId);
            log.setAdminName(adminName);
            log.setAdminId(adminId);
        }

        logService.save(log);

        Boolean Bool = service.updateById(byId);

        if (users.getLevel().getValue() == 3 && status.getValue() == 1 && Bool) {

            this.levelUp(4, uid);

            this.deleteInviter(uid);

        }

        return ResponseResult.success(Bool);
    }

    @PostMapping("/getDetail")
    @ApiOperation("金牌推广商单条详情")
    public ResponseResult getDetail(Integer uid) {
        GoldPromoterReviewReponse goldInfoById = service.getGoldInfoById(uid);
        if (ObjectUtil.isNotNull(goldInfoById)) {
            return ResponseResult.success(goldInfoById);
        }
        return ResponseResult.error("未查询到相关记录!");
    }

    @PostMapping("/batchUpdate")
    @ApiOperation("金牌推广商批量驳回/审核")
    @Transactional
    public ResponseResult batchUpdate(String[] ids, String remark, CheckStatus status){
        Long adminId = ServletUtils.getLoginId();
        String adminName = ServletUtils.getLoginName();
        QueryWrapper wrapper=new QueryWrapper();
        wrapper.in("member_id",ids);
        List<JmGoldPromoterReview> list = service.list(wrapper);
        List<JmPromoterCheckLog> logs=new ArrayList<>();

        if(list.size()==0) return ResponseResult.error("未查询到相关记录！");
        final JmGoldPromoterReview ja = list.get(0);

        for (int i = 0; i < list.size(); i++) {
            if(ja.getStatus()!=list.get(i).getStatus()){
                return ResponseResult.error("所选记录存在不同审核阶段，请检查！");
            }
        }
        ja.setMessage(remark);
        CheckStatus checkStatus = ja.getStatus();
        if(checkStatus.equals(CheckStatus.未通过)){
            return ResponseResult.error("未通过记录，不允许操作!");
        }

        if(ja.getStatus().equals(CheckStatus.待审核)){
            ja.setStatus(status);
        }else if(ja.getStatus().equals(CheckStatus.已通过)){
            ja.setStatus(CheckStatus.未通过);
        }

        list.stream().forEach( i->{
            i.setMessage(ja.getMessage());
            i.setStatus(ja.getStatus());
            i.setShenheTime(LocalDateTime.now());
            i.setAdminId(adminId);
            JmPromoterCheckLog log=new JmPromoterCheckLog();
            BeanUtils.copyProperties(i,log);
            log.setAdminName(adminName);
            logs.add(log);
        });
        logService.saveBatch(logs);
        return ResponseResult.success(service.updateBatchById(list));
    }

    @PostMapping("/checkGold")
    @ApiOperation("审核条件是否达成")
    public ResponseResult checkGold(Integer uid) {

        //检查是否有申请过

        JmGoldPromoterReview gold = service.getById(uid);

        if (ObjectUtil.isEmpty(gold)) {
            return ResponseResult.error("抱歉，未查询到有申请记录！");
        };

        JmUser byId = userService.checkUserExist(uid);
        JmUserLevelConfig obj = this.getLevelConfig(byId.getLevel().getValue() == 4 ? byId.getLevel().getValue() : byId.getLevel().getValue()+1 );

        ListLevelDataReponse LevelYouxiu = service.getListLevel(uid, LevelCondition.金牌新增时间.getValue());

        Boolean yeji = LevelYouxiu.getSales() == null ? false :LevelYouxiu.getSales().compareTo(obj.getSales()) >= 0 ;

        Boolean count1 = LevelYouxiu.getJinpaiCount() == null ? false : LevelYouxiu.getJinpaiCount() >= obj.getChildrenNum();

        Boolean count2 = LevelYouxiu.getCount2()== null ? false : LevelYouxiu.getCount2() >=  obj.getAddNum();

        if (yeji && count1 && count2) {
            return ResponseResult.success(true);

        }

        this.update(uid, "售后行为导致不符合升级条件,系统审核不通过!", CheckStatus.未通过);

        return ResponseResult.success(false);

    }

}
